<script setup lang="ts">

import {deleteStores} from "@/api/store";

/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "AuditRule",
  inheritAttrs: false,
});
import {
  getAuditRulePage,
  getAuditRuleForm,
  saveAuditRule,
  deleteAuditRule,
  updateAuditRule
} from "@/api/auditRule";

import { AuditRuleQuery, RuleForm } from "@/api/auditRule/types";
import {getDictOptions} from "@/api/dict";
import {listRoleOptionsCode} from "@/api/role";

const queryFormRef = ref(ElForm); // 查询表单
const dataFormRef = ref(ElForm); // 规则表单
const dictList = ref<OptionType[]>();
const roleList = ref<OptionType[]>();

const dialog = reactive<DialogOption>({
	visible: false,
});

const formData = reactive<RuleForm>({});

const loading = ref(false);
const ids = ref([]);
const total = ref(0);

const queryParams = reactive<AuditRuleQuery>({
	pageNum: 1,
	pageSize: 20,
});
const auditRuleList = ref<[]>();

const rules = reactive({
	ruleCode: [{ required: true, message: "请输入规则编码", trigger: "blur" }],
	ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	getAuditRulePage(queryParams)
	.then(({ data }) => {
		auditRuleList.value = data.list;
		total.value = data.total;
	})
	.finally(() => {
		loading.value = false;
	});
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 打开规则表单弹窗
 *
 * @param ruleId 规则ID
 */
function openDialog(ruleId?: number) {
	dialog.visible = true;
	if (ruleId) {
		dialog.title = "修改规则";
		getAuditRuleForm(ruleId).then(({ data }) => {
			Object.assign(formData, data);
		});
	} else {
		dialog.title = "新增规则";
	}
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dataFormRef.value.resetFields();
	dataFormRef.value.clearValidate();
	formData.id = undefined;
}

/**
 * 删除字典类型
 */
function handleDelete(ruleId?: number) {
	const dictTypeIds = [ruleId || ids.value].join(",");
	if (!dictTypeIds) {
		ElMessage.warning("请勾选删除项");
		return;
	}

	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		deleteAuditRule(dictTypeIds).then(() => {
			ElMessage.success("删除成功");
			resetQuery();
		});
	});
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
	dataFormRef.value.validate((valid: any) => {
		if (valid) {
			const ruleId = formData.id;
			loading.value = true;
			if (ruleId) {
				updateAuditRule(ruleId, formData)
						.then(() => {
							ElMessage.success("修改规则成功");
							closeDialog();
							handleQuery();
						})
						.finally(() => (loading.value = false));
			} else {
				saveAuditRule(formData)
						.then(() => {
							ElMessage.success("新增规则成功");
							closeDialog();
							handleQuery();
						})
						.finally(() => (loading.value = false));
			}
		}
	});
}, 3000);

/**
 * 获取字典类型的数据项
 *
 * @param typeCode 字典类型编码
 */
function getDictOptionList() {
	getDictOptions('jgfl').then((response) => {
		dictList.value = response.data;
	});
}

function getDictName(key?: string) {
	if (dictList != undefined) {
		if (dictList.value != undefined) {
			for (let dict of dictList.value) {
				if (dict != undefined && dict.value+'' == key) {
					return dict.label
				}
			}
		}
	}
	return ''
}

function getRoleName(key?: string) {
	if (roleList != undefined) {
		if (roleList.value != undefined) {
			for (let role of roleList.value) {
				if (role != undefined && role.value+'' == key) {
					return role.label
				}
			}
		}
	}
	return ''
}

/**
 * 获取角色下拉列表
 */
async function getRoleOptions() {
	listRoleOptionsCode().then((response) => {
		roleList.value = response.data;
	});
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
}

function format_number(symbol: string, data: number) {
	if (symbol !== undefined && symbol !== null && data !== 0) {
		return symbol + (data + '')
	}else if (data !== 0) {
		return data
	}else{
		return ''
	}
}

onMounted(() => {
  handleQuery(); // 初始化标准账单配置列表数据
  getDictOptionList()
  getRoleOptions()
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col>
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
			  <el-form-item label="关键字" prop="keywords">
				  <el-input
						  v-model="queryParams.keywords"
						  placeholder="规则编码/规则名称"
						  clearable
						  style="width: 200px"
						  @keyup.enter="handleQuery"
				  />
			  </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button>
			</el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
			<template #header>
			<el-button
				v-hasPerm="['sys:auditRule:add']"
				type="success"
				@click="openDialog()"
			><i-ep-plus />新增</el-button
			>
			<el-button
				type="danger"
				v-hasPerm="['sys:auditRule:delete']"
				:disabled="ids.length === 0"
				@click="handleDelete()"
			><i-ep-delete />删除</el-button
			>
			</template>

          <el-table
			size="small"
			:height="auditRuleList && auditRuleList.length > 0 ? 580 : 100"
			:header-row-style="{color: 'dimgray'}"
            v-loading="loading"
            :data="auditRuleList"
			border
			@selection-change="handleSelectionChange"
          >
			  <el-table-column type="selection" width="55" align="center" />
			  <el-table-column
					  label="规则编码"
					  align="center" show-overflow-tooltip
					  prop="ruleCode"
			  />

			  <el-table-column
					  label="规则名称"
					  align="center" show-overflow-tooltip
					  prop="ruleName"
			  />
			  <el-table-column
					  label="核销优先级"
					  align="center" show-overflow-tooltip
					  prop="priority"
			  />
			  <el-table-column
					  label="结果分类"
					  align="center" show-overflow-tooltip
			  >
				  <template #default="scope">
					  {{getDictName(scope.row.resultType)}}
				  </template>
			  </el-table-column>
			  <el-table-column
					  label="责任归属"
					  align="center" show-overflow-tooltip
					  prop="liability"
			  >
				  <template #default="scope">
					  {{getRoleName(scope.row.liability)}}
				  </template>
			  </el-table-column>
			  <el-table-column
					  label="订单核销细类"
					  align="center" show-overflow-tooltip
					  prop="orderAuditType"
					  width="180"
			  ></el-table-column>
			  <el-table-column
					  label="应收账款余额"
					  align="center" show-overflow-tooltip
			  >
				  <template #default="scope">{{format_number(scope.row.receiveCountSymbol,  scope.row.receiveCount)}}</template>
			  </el-table-column>
			  <el-table-column
					  label="业务日期vs查询日期"
					  align="center" show-overflow-tooltip
			  >
				  <template #default="scope">{{format_number(scope.row.dateConfigSymbol,  scope.row.dateConfig)}}</template>
			  </el-table-column>
			  <el-table-column
					  label="收款金额-发货金额"
					  align="center" show-overflow-tooltip
			  >
				  <template #default="scope">{{format_number(scope.row.moneyDiffConfigSymbol,  scope.row.moneyDiffConfig)}}</template>
			  </el-table-column>
			  <el-table-column fixed="right" label="操作" align="center" width="150">
				  <template #default="scope">
					  <el-button
							  v-hasPerm="['sys:auditRule:edit']"
							  type="primary"
							  link
							  size="small"
							  @click.stop="openDialog(scope.row.id)"
					  ><i-ep-edit />编辑</el-button
					  >
					  <el-button
							  v-hasPerm="['sys:auditRule:delete']"
							  type="primary"
							  link
							  size="small"
							  @click.stop="handleDelete(scope.row.id)"
					  ><i-ep-delete />删除</el-button
					  >
				  </template>
			  </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
		  <el-dialog
			  v-model="dialog.visible"
			  :title="dialog.title"
			  width="600px"
			  :close-on-click-modal="false"
			  @close="closeDialog"
		  >
			  <el-form
				  ref="dataFormRef"
				  :model="formData"
				  :rules="rules"
				  label-width="160px"
			  >
			  <el-form-item label="规则编码" prop="ruleCode">
				  <el-input v-model="formData.ruleCode" placeholder="请输入规则编码" clearable :disabled="formData.id !== undefined"/>
			  </el-form-item>
			  <el-form-item label="规则名称" prop="ruleName">
				  <el-input v-model="formData.ruleName" placeholder="请输入规则名称" clearable/>
			  </el-form-item>
			  <el-form-item label="核销优先级" prop="priority">
				  <el-input-number v-model="formData.priority" :min="1" clearable/>
			  </el-form-item>
			  <el-form-item label="结果分类" prop="resultType">
				  <dictionary v-model="formData.resultType" type-code="jgfl" clearable/>
			  </el-form-item>
			  <el-form-item label="责任归属" prop="liability">
				  <el-select class="yz-el-select" v-model="formData.liability" placeholder="请选择" clearable>
					  <el-option
							  v-for="item in roleList"
							  :key="item.value"
							  :label="item.label"
							  :value="item.value"
					  />
				  </el-select>
			  </el-form-item>
			  <el-form-item label="订单核销细类" prop="orderAuditType">
				  <el-input v-model="formData.orderAuditType" placeholder="请输入订单核销细类" clearable/>
			  </el-form-item>
			  <el-form-item label="应收账款余额" prop="receiveCount">
				  <el-input-number v-model="formData.receiveCount" clearable/>
			  </el-form-item>
			  <el-form-item label="业务日期vs查询日期" prop="dateConfig">
				  <el-input-number v-model="formData.dateConfig" clearable/>
			  </el-form-item>
			  <el-form-item label="收款金额-发货金额" prop="moneyDiffConfig">
				  <el-input-number v-model="formData.moneyDiffConfig" clearable/>
			  </el-form-item>
			  </el-form>
			  <template #footer>
				  <div class="dialog-footer">
					  <el-button type="primary" @click="handleSubmit">确 定</el-button>
					  <el-button @click="closeDialog">取 消</el-button>
				  </div>
			  </template>
		  </el-dialog>
      </el-col>
    </el-row>


  </div>
</template>
